package StringAlgorithm;

import java.util.HashMap;
import java.util.Map;

public class leet_8 {
    public static void main(String[] args) {
        String s = "9223372036854775808";
        Solution_8 p = new Solution_8();
        int value = p.myAtoi(s);
        System.out.println(value);
    }

}

class Solution_8 {
    /**
     * DFA 状态机转换
     * 起始状态是start 然后转到 signal 然后转到 numbers 最后转到end
     * 这是理想状态其中任何一个状态都可以随时转到 end
     */
    public int myAtoi(String s) {
        if(s.length()==0){return 0;}

        long result = 0;
        // 默认是正
        int signed = 1;
        String state = "start";
        Map<String, String[]> table = new HashMap<String, String[]>() {{
            put("start", new String[]{"start", "signed", "in_number", "end"});
            put("signed", new String[]{"end", "end", "in_number", "end"});
            put("in_number", new String[]{"end", "end", "in_number", "end"});
            put("end", new String[]{"end", "end", "end", "end"});
        }};

        // 遍历字符串
        for(int i=0; i<s.length(); i++){
            char charValue = s.charAt(i);
            int index = analysisWords(charValue);

            String[] stateStrings = table.get(state);
            state = stateStrings[index];
            if("signed".equals(state)){
                if(charValue=='-'){
                    signed = -1;
                }
            }
            if("in_number".equals(state)){
                // 可能传入的字符超过 long的最大值，把判断推前
                result = result*10 + (charValue-'0');
                if(signed==1){
                    result = Math.min(result, (long) Integer.MAX_VALUE);
                }else{
                    result = Math.min(result, -(long) Integer.MIN_VALUE);
                }
            }

            if("end".equals(state)){
                return (int)result*signed;
            }

        }

        return (int)result*signed;
    }

    /**
     * 查看string 当前位置 char 的情况
     * @param s 传入的char值
     * @return 其状态需要转换的索引
     */
    public int analysisWords(char s){
        if(' '== s){
            return 0;
        }else if('+'==s){
            return 1;
        }else if('-'==s){
            return 1;
        }else if(Character.isDigit(s)){
            return 2;
        }
        return 3;
    }

}